package org.i_plus.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.i_plus.Assistance;
import org.i_plus.model.TarotBean;
import org.i_plus.model.services.TarotService;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.google.gson.Gson;

public class InsertTarotServlet extends HttpServlet {
	private TarotService service;
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doGet(req, resp);
	}

	@Override
	public void init() throws ServletException {
		ServletContext application = this.getServletContext();
		ApplicationContext context=
				WebApplicationContextUtils.getWebApplicationContext(application);
		this.service = (TarotService)context.getBean("tarotService");
		super.init();
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		Map<String, String> errors = new HashMap<String, String>();
		req.setAttribute("errors", errors);
		
		String num = req.getParameter("num");
		
		TarotBean bean = new TarotBean();
		bean.setNum(Integer.parseInt(num));
		
		TarotBean feedback = service.selectByNum(bean);
		if(feedback==null){
			errors.put("taroterror", "抽牌過程發生錯誤，請在試一次");
		}else{
			req.setAttribute("tarot", feedback);
		}
		//之後用專題的靜態方法
		String blob  = Assistance.photoByteToImgString("image/jpeg", feedback.getPic());
		String temp[] = {feedback.getName(),blob,feedback.getContent()};
		Gson gson = new Gson();
		String result = gson.toJson(temp);
		
		resp.setCharacterEncoding("UTF-8");
		resp.getWriter().print(result);
		return;		
	}

	
}
